import Vue from 'vue'
import store from '@/store'
/**
 * 元素单向移动
*/
Vue.directive('dragpin', {
    bind: function(el, binding, vnode){
        var position = ['top', 'right', 'bottom', 'left'].find(v => v === binding.arg) || 'top';

        el.onmousedown = function(e){
            let left = e.clientX - el.offsetLeft;
            let top = e.clientY - el.offsetTop;
            e.preventDefault();
            e.stopPropagation();

            document.onmousemove = function(e){
                document.onselectstart = () => {return false};
                if(['top', 'bottom'].indexOf(position) !== -1) {
                    el.style.left = e.clientX - left + 'px';
                }
                if(['right', 'left'].indexOf(position) !== -1) {
                    el.style.top = e.clientY - top + 'px';
                }
            }
            document.onmouseup = function(e){
                document.onselectstart = null;
                document.onmousemove = null;
                document.onmouseup = null;
            }
        }
    }
})

const valueType = function(value) {
    return Object.prototype.toString.call(value).slice(8, -1)
}
const has = function(permissions = [], value) {
    if(!permissions) return false;

    if(valueType(value) === 'Boolean') {
        return value
    }
    if(valueType(value) === 'Number') {
        return permissions.indexOf(value) !== -1
    }
    if(valueType(value) === 'String') {
        return permissions.indexOf(value) !== -1
    }
    if(valueType(value) === 'Function') {
        return has(permissions, value(permissions, value))
    }
    /**
     * object 表示 ‘与’
     * { key1: true, key2: false } => permissions 里面存在 key1 并且没有 key2
    */
    if(valueType(value) === 'Object') {
        return Object.keys(value).every(k => value[k] ? has(permissions, k) : !has(permissions, k))
    }
    //array 元素之间表示 ‘或’
    if(valueType(value) === 'Array') {
        return value.some(v => has(permissions, v))
    }

    return false
}
/**
 * 权限控制 可通过 value 和 permissions 权限判断是否显示
*/
Vue.directive('acl', {
    inserted: function(el, binding, vnode) {
        if(!el._directive_) {
            el._directive_ = {}  
        }
        el._directive_.parentNode = el.parentNode

        if(binding.value !== undefined && binding.value !== null) {
            if(!has(store.state.auth.permissions, binding.value)) {
                el.parentNode && el.parentNode.removeChild(el)
            }
        }
    },
    update: function(el, binding, vnode) {
        if(binding.value !== undefined && binding.value !== null && has(store.state.auth.permissions, binding.value)) {
            if(el._directive_ && el._directive_.parentNode) {
                el._directive_.parentNode.appendChild(el)
            }
        } else {
            el.parentNode && el.parentNode.removeChild(el)
        }
    }
})